import Vue from 'vue';
import Router, { Route } from 'vue-router';
import { constantRouterMap, asyncRouterMap } from '@/routes';
import storage from 'store'
import { permission } from '@/store/modules/permission'
import NProgress from 'nprogress' // progress bar
import '@/components/src/NProgress/nprogress.less'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import {
  ACCESS_TOKEN
} from '@/config/constant'

Vue.use(Router);

let router = new Router({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: [
    ...constantRouterMap,
    // ...asyncRouterMap
  ],
});

const whiteList: string[] = []
const loginRoutePath = '/user/login'
const defaultRoutePath = '/'

let flag = false;

// 注入拦截器
router.beforeEach((to: Route, from: Route, next) => {
  NProgress.start() // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`))
  console.log(to.path, from.path)
  /* has token */
  if (sessionStorage.getItem(ACCESS_TOKEN)) {
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
    } else {
      if (!permission.dynamicRoutes.length) {
        if (flag) {
          next()
          NProgress.done()
        }
        flag = true
        permission.getPermissionList().then(() => {
          // const redirect = decodeURIComponent(from.query.redirect || to.path)
          // if (to.path === redirect) {
          //   // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          //   next({ ...to, replace: true })
          // } else {
          //   // 跳转到目的路由
          //   next({ path: redirect })
          // }
          next({
            path: to.path,
          })
          NProgress.done()
        }).catch(() => {
          next()
          NProgress.done()
        }).finally(() => {
          flag = false
        })
      } else {
        next()
        NProgress.done()
      }

    }
  } else {
    
    if (to.name && whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      if (to.path === loginRoutePath) {
        next()
      } else {
        next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      }
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

export default router
